import json
import os
from typing import Dict, List, Optional
from src.logger import logger

class PasswordStorage:
    """密码存储数据访问类"""
    
    def __init__(self, storage_path: str = "~/.mysqlpass/passwords.json"):
        """初始化存储类"""
        # 扩展路径中的~为用户主目录
        self.storage_path = os.path.expanduser(storage_path)
        # 确保存储目录存在
        self._ensure_directory_exists()
    
    def set_storage_path(self, storage_path: str):
        """设置存储路径"""
        self.storage_path = os.path.expanduser(storage_path)
        self._ensure_directory_exists()
    
    def _ensure_directory_exists(self):
        """确保存储目录存在"""
        os.makedirs(os.path.dirname(self.storage_path), exist_ok=True)
    
    def read_passwords(self) -> Dict[str, Dict[str, str]]:
        """从存储文件读取密码配置"""
        try:
            if os.path.exists(self.storage_path):
                with open(self.storage_path, 'r', encoding='utf-8') as f:
                    return json.load(f)
        except (json.JSONDecodeError, IOError) as e:
            logger.error(f"读取密码配置时出错: {e}")
        return {}
    
    def write_passwords(self, passwords: Dict[str, Dict[str, str]]) -> bool:
        """将密码配置写入存储文件"""
        try:
            with open(self.storage_path, 'w', encoding='utf-8') as f:
                json.dump(passwords, f, indent=4, ensure_ascii=False)
            logger.info(f"成功写入密码配置到 {self.storage_path}")
            return True
        except IOError as e:
            logger.error(f"写入密码配置时出错: {e}")
            return False
    
    def get_connection_names(self) -> List[str]:
        """获取所有连接名称列表"""
        passwords = self.read_passwords()
        return list(passwords.keys())
    
    def get_connection_details(self, name: str) -> Optional[Dict[str, str]]:
        """获取指定连接的详细配置"""
        passwords = self.read_passwords()
        return passwords.get(name)
    
    def add_or_update_connection(self, name: str, host: str, port: str, username: str, password: str) -> bool:
        """添加或更新连接配置"""
        passwords = self.read_passwords()
        passwords[name] = {
            'host': host,
            'port': port,
            'username': username,
            'password': password
        }
        return self.write_passwords(passwords)
    
    # 以下是为了兼容mysql_password_manager.py中的方法名而添加的包装方法
    def list_connections(self) -> list:
        """列出所有保存的连接名称"""
        return self.get_connection_names()
    
    def get_connection(self, name: str) -> Optional[Dict[str, str]]:
        """获取MySQL连接配置"""
        return self.get_connection_details(name)
    
    def add_connection(self, name: str, host: str, port: str, username: str, password: str) -> bool:
        """添加或更新MySQL连接密码"""
        return self.add_or_update_connection(name, host, port, username, password)
    
    def delete_connection(self, name: str) -> bool:
        """删除指定连接配置"""
        passwords = self.read_passwords()
        if name in passwords:
            del passwords[name]
            return self.write_passwords(passwords)
        logger.warning(f"连接 {name} 不存在，无法删除")
        return False

# 创建一个默认的密码存储实例
password_storage = PasswordStorage()